package com.linkpow.smartelevator.config;

import com.linkpow.smartelevator.common.ErrorMessage;
import com.linkpow.smartelevator.common.RespBase;
import com.linkpow.smartelevator.exception.PlatformException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

/**
 * @ClassName GlobalExceptionHandler
 * @Description 统一Controller异常处理
 * @Author 王丹
 * @Date 2019/11/25 14:06
 * @Version 1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(value=Exception.class)
    @ResponseBody
    public RespBase errorHandler(Exception e, HttpServletRequest req, HttpServletResponse response){
        logger.error("API服务发生错误",e);
        RespBase respBase = new RespBase();
        String code = ErrorMessage.FAIL.getMessageCode(), message = ErrorMessage.FAIL.getMessageValue();
        if(e instanceof PlatformException){
            code = ((PlatformException) e).getCode();
            message = e.getMessage();
        }else if(e instanceof ValidationException){
            logger.warn("数据验证发生异常",e);
            code = (ErrorMessage.ERROR_VALIDATION.getMessageCode());
            if(e instanceof ConstraintViolationException){
                ConstraintViolationException e1 = (ConstraintViolationException)e;
                message = (e1.getConstraintViolations().stream().findFirst().get().getMessage());
            }else {
                message = (e.getMessage());
            }
        }else if(e instanceof MethodArgumentNotValidException){
            logger.warn("数据验证发生异常",e);
            code = (ErrorMessage.ERROR_VALIDATION.getMessageCode());
            MethodArgumentNotValidException e1 = (MethodArgumentNotValidException)e;
            message = (e1.getBindingResult().getFieldError().getDefaultMessage());
        }
        respBase.setCode(code);
        respBase.setMsg(message);
        return respBase;
    }
}
